package com.esreport.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esreport.Utils.GuavaCacheUtil;
import com.esreport.Utils.HttpSessionUtils;
import com.esreport.Utils.PublisDateCompare;
import com.esreport.dto.ArticleInformation;
import com.esreport.service.OtherSourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class OtherSourceServiceImpl implements OtherSourceService {

    @Value("${ucenter.url}")
    public String ucenterURL;
    @Value("${conf.url}")
    public String confURL;
    @Value("${rec.url}")
    public String recURL;
    @Value("${society.url}")
    public String societyURL;

    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();

    @Override
    @SuppressWarnings("unchecked")
    public List<ArticleInformation> getTopArticle(Integer siteId, Integer num, String startTime, String endTime) throws IOException, ParseException {
//        List<ArticleInformation> tops = (List<ArticleInformation>) GuavaCacheUtil.get("tops_" + siteId + "_" + num + startTime + "_" + endTime);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if (tops == null || tops.size() == 0) {
        List<ArticleInformation> list = new ArrayList<>();
        String cmsJson;
        JSONArray cmsArray;
        JSONArray recArray;
        //请求配置系统  获取cms域名
        Map<String, String> cmsParam = new HashMap<>();
        cmsParam.put("siteId", siteId.toString());
        String cmsURL = getCmsUrl(siteId);
        cmsParam.put("method", "getArticleByTops");
        cmsParam.put("startTime", startTime);
        cmsParam.put("endTime", endTime);
        cmsParam.put("num", num.toString());
        cmsJson = HttpSessionUtils.httpPost(client, cmsURL, cmsParam);
        //log.info(cmsJson);
        //System.out.println("cmsJson----->"+cmsJson);
        cmsArray = JSON.parseArray(cmsJson);
        for (Object o : cmsArray) {
            ArticleInformation ai = new ArticleInformation();
            JSONObject cmsArticle = (JSONObject) o;
            ai.setId(cmsArticle.getInteger("ID"));
            ai.setHitCount(cmsArticle.getInteger("HitCount"));
            ai.setTitle(cmsArticle.getString("Title"));
            ai.setThumb(cmsArticle.getString("Logo"));
            ai.setPublishDate(cmsArticle.getString("PublishDate"));
            ai.setType("CMS");
            list.add(ai);
        }
        /*Map<String, String> recParam = new HashMap<>();
        String method = "/getClickRanking";
        //开始时间结束时间都不为空
        if ((startTime != null && !"".equals(startTime)) && (endTime != null && !"".equals(endTime))) {
            recParam.put("startTime", String.valueOf(sf.parse(startTime).getTime()));
            recParam.put("endTime", String.valueOf(sf.parse(endTime).getTime()));
            method = "/getVideoForTime";
        }
        //结束时间不为空，开始时间为空
        if ((endTime != null && !"".equals(endTime)) && (startTime == null || "".equals(startTime))) {
            recParam.put("endTime", String.valueOf(sf.parse(endTime).getTime()));
            recParam.put("startTime", String.valueOf(sf.parse("1970-01-01 00:00:00").getTime()));
            method = "/getVideoForTime";
        }
        //开始时间不为空，结束时间为空
        if ((startTime != null && !"".equals(startTime)) && (endTime == null || "".equals(endTime))) {
            recParam.put("startTime", String.valueOf(sf.parse(startTime).getTime()));
            recParam.put("endTime", String.valueOf(System.currentTimeMillis()));
            method = "/getVideoForTime";
        }
        recParam.put("siteId", siteId.toString());
        recParam.put("type", "1");
        recParam.put("page", "1");
        recParam.put("number", num.toString());
        String recJson = HttpSessionUtils.httpPost(client, recURL + method, recParam);
        //log.info(recJson);
        //System.out.println("recJson----->"+recJson);
        JSONObject obj = JSON.parseObject(recJson);
        if (obj.getInteger("code") == 200) {
            recArray = obj.getJSONArray("data");
            for (Object o : recArray) {
                ArticleInformation ai = new ArticleInformation();
                JSONObject recArticle = (JSONObject) o;
                ai.setThumb(recArticle.getString("Logo"));
                ai.setPublishDate(recArticle.getString("PublishDate"));
                ai.setTitle(recArticle.getString("Title"));
                ai.setHitCount(recArticle.getInteger("HitCount"));
                ai.setId(recArticle.getInteger("ID"));
                ai.setType("REC");
                list.add(ai);
            }
        }*/
        Collections.sort(list);
        if (list.size() > num) {
            list = list.subList(0, num);
        }
//            tops = list;
//            GuavaCacheUtil.put("tops_" + siteId + "_" + num + startTime + "_" + endTime, list);
//        }
        return list;
    }


    @Override
    public JSONObject getArticleContent(Integer siteId, Integer articleId, String type) throws IOException {
        String result;
        //if (type.equals("CMS")) {//取cms新闻
        //请求配置系统  获取cms域名
        Map<String, String> cmsParam = new HashMap<>();
        cmsParam.put("siteId", siteId.toString());
        String cmsURL = getCmsUrl(siteId);
        cmsParam.put("method", "getMomentArticle");
        cmsParam.put("ID", articleId.toString());
        result = HttpSessionUtils.httpPost(client, cmsURL, cmsParam);
        /*} else {//取rec新闻
            Map<String, String> recParam = new HashMap<>();
            recParam.put("newsId", articleId.toString());
            recParam.put("siteId", siteId.toString());
            result = HttpSessionUtils.httpPost(client, recURL + "/newsDetail", recParam);
        }*/
        //log.info(result);
        return JSON.parseObject(result);
    }


    @Override
    public List<ArticleInformation> getArticleListOrderByPublishDate(Integer siteId, Integer num) throws IOException {
        List<ArticleInformation> tops = (List<ArticleInformation>) GuavaCacheUtil.get("tops_publish_date_desc" + siteId + "_" + num);
        if (tops == null || tops.size() == 0) {
            List<ArticleInformation> list = new ArrayList<>();
            String cmsJson;
            JSONArray cmsArray;
            JSONArray recArray;
            //请求配置系统  获取cms域名
            Map<String, String> cmsParam = new HashMap<>();
            cmsParam.put("siteId", siteId.toString());
            String cmsURL = getCmsUrl(siteId);
            cmsParam.put("method", "getArticleListOrderByPublishDate");
            cmsParam.put("num", num.toString());
            cmsJson = HttpSessionUtils.httpPost(client, cmsURL, cmsParam);
            //log.info(cmsJson);
            cmsArray = JSON.parseArray(cmsJson);
            for (Object o : cmsArray) {
                ArticleInformation ai = new ArticleInformation();
                JSONObject cmsArticle = (JSONObject) o;
                ai.setId(cmsArticle.getInteger("ID"));
                ai.setHitCount(cmsArticle.getInteger("HitCount"));
                ai.setTitle(cmsArticle.getString("Title"));
                ai.setThumb(cmsArticle.getString("Logo"));
                ai.setPublishDate(cmsArticle.getString("PublishDate"));
                ai.setType("CMS");
                list.add(ai);
            }
            /*Map<String, String> recParam = new HashMap<>();
            String method = "/newsBySite";
            recParam.put("siteId", siteId.toString());
            recParam.put("num", num.toString());
            String recJson = HttpSessionUtils.httpPost(client, recURL + method, recParam);
            //log.info(recJson);
            JSONObject obj = JSON.parseObject(recJson);
            if (obj.getInteger("code") == 200) {
                recArray = obj.getJSONArray("data");
                for (Object o : recArray) {
                    ArticleInformation ai = new ArticleInformation();
                    JSONObject recArticle = (JSONObject) o;
                    ai.setThumb(recArticle.getString("Logo"));
                    ai.setPublishDate(recArticle.getString("PublishDate"));
                    ai.setTitle(recArticle.getString("Title"));
                    ai.setHitCount(recArticle.getInteger("HitCount"));
                    ai.setId(recArticle.getInteger("ID"));
                    ai.setType("REC");
                    list.add(ai);
                }
            }*/
            Collections.sort(list, new PublisDateCompare());
            if (list.size() > num) {
                list = list.subList(0, num);
            }
            tops = list;
            GuavaCacheUtil.put("tops_publish_date_desc" + siteId + "_" + num, list);
        }
        return tops;
    }

    @Override
    public String getCmsUrl(Integer siteId) throws IOException {
        //请求配置系统  获取cms域名
        Map<String, String> param = new HashMap<>();
        param.put("siteId", siteId.toString());
        String config = HttpSessionUtils.httpPost(client, confURL + "/getConfig", param);
        //log.info(config);
        JSONObject configJson = JSON.parseObject(config);
        if (configJson.getInteger("code") != 200) {
            throw new RuntimeException("请求配置系统异常");
        }
        return configJson.getJSONObject("data").getString("cmsUrl");
    }

    @Override
    public JSONObject getDangShiTopicData(Integer siteId) throws IOException, RuntimeException {
        Map<String, String> param = new HashMap<>();
        param.put("siteId", siteId.toString());
        String topicDataInfo = HttpSessionUtils.httpPost(client, societyURL + "/site/getDangJianData", param);
        JSONObject topicData = JSON.parseObject(topicDataInfo);
        if (topicData.getInteger("code") != 0) {
            throw new RuntimeException("请求圈子数据失败");
        }
        return topicData.getJSONObject("content");
    }
}
